package io.renren.modules.sq.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.RandomUtils;
import io.renren.common.utils.ResponseData;
import io.renren.modules.sq.dto.CodeListDto;
import io.renren.modules.sq.dto.SysAuthDto;
import io.renren.modules.sq.entity.SqSystemAuthorizationCodeEntity;
import io.renren.modules.sq.entity.SqSystemEntity;
import io.renren.modules.sq.service.SqSystemAuthorizationCodeService;
import io.renren.modules.sq.service.SqSystemService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统表
 *
 * @author txw_cyl
 * @email sunlightcs@gmail.com
 * @date 2022-05-14 19:29:39
 */
@Api(tags = "授权管理")
@RestController
@RequestMapping("sys/sqmanage")
public class SqManageController {
    @Autowired
    private SqSystemService sqSystemService;
    @Autowired
    private SqSystemAuthorizationCodeService sqSystemAuthorizationCodeService;

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("获取当前用户的可用系统应用以及版本列表")
    @PostMapping("/getusersystemlist")
    @ApiImplicitParam(name = "userId",value = "用户id",paramType = "query",dataType = "String",required = true)
    public ResponseData<List<SqSystemEntity>> getusersystemlist(@RequestParam("userId") String userId){
        //获取用户
        SysUserEntity user = sysUserService.getById(userId);
        if (user == null)   return ResponseData.success("用户不存在！", false);

        List<SqSystemEntity> res = null;
        if(user.getUserId() == user.getCreateUserId()){
            //最高级用户，返回所有系统
            res = sqSystemService.getSystemList();
        }else {
            //其余用户
            res = sqSystemService.getUserSystemListByUserid(user.getUserId());
        }
        return ResponseData.success(res);
    }

    @ApiOperation("获取当前用户的授权码下的生成的授权码列表")
    @PostMapping("/getusercodelist")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "systemEditionId",value = "应用版本id",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "username",value = "创建者姓名",paramType = "query",dataType = "String",required = false)
    })
    public ResponseData<List<CodeListDto>> getusercodelist(@RequestParam("userId") String userId,
                                                           @RequestParam("systemEditionId") String systemEditionId,
                                                           @RequestParam("username") String username){
        //获取用户
        SysUserEntity user = sysUserService.getById(userId);
        if (user == null)   return ResponseData.success("用户不存在！", false);

        List<CodeListDto> res = null;
        if(user.getUserId() == user.getCreateUserId()){
            //最高级用户，返回指定系统创建授权码的记录数
            res = sqSystemAuthorizationCodeService.getadmincodelist(systemEditionId, username);
        }else {
            //其余用户
            res = sqSystemAuthorizationCodeService.getadmincodelistbyuid(user.getUserId(), systemEditionId, username);
        }
        for (CodeListDto codeDto:res) {
            int usednum = 0;
            List<SqSystemAuthorizationCodeEntity> codes = codeDto.getCodes();
            for (SqSystemAuthorizationCodeEntity code:codes)
                if(code.getUsed() == 1) ++usednum;
            codeDto.setUsedNum(usednum);
            codeDto.setUnusedNum(codes.size()-usednum);
        }
        return ResponseData.success(res);
    }

    @ApiOperation("下载授权码文件")
    @PostMapping("/getcodetxt")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "创建者id",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "systemEditionId",value = "系统版本id",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "createCodeNum",value = "添加记录次数（1开始）",paramType = "query",dataType = "int",required = true)
    })
    public String getcodetxt(@RequestParam("userId") String userId,
                             @RequestParam("systemEditionId") String systemEditionId,
                             @RequestParam("createCodeNum") int createCodeNum,
                             HttpServletResponse response) throws Exception {
        // 创建文件流
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String currentDate = simpleDateFormat.format(new Date());
        String filename = "授权码列表" + "_" + userId + "_" + currentDate;
        File tmpFile = new File(filename);
        if (tmpFile.exists())   tmpFile.delete();
        tmpFile.createNewFile();
        BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile));
        //获取授权码列表
        List<SqSystemAuthorizationCodeEntity> codeList = sqSystemAuthorizationCodeService.list(new QueryWrapper<SqSystemAuthorizationCodeEntity>().eq("user_id", userId).eq("system_edition_id", systemEditionId).eq("create_code_num", createCodeNum));
        for (SqSystemAuthorizationCodeEntity codeEntity: codeList) {
            String codeRow = codeEntity.printCodeInfoRow();
            bw.write(codeRow);
        }
        bw.flush();  //清除缓存
        bw.close();

        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(tmpFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = response.getOutputStream();
        int i = bis.read(buffer);
        while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
        }
        bis.close();
        fis.close();
        //删除文件
        tmpFile.delete();
        return null;
    }
}
